import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-10-08
 * Time: 19:09
 */
public class UdpEchoServer {
    private DatagramSocket socket = null;
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //1.接受请求数据包
            DatagramPacket requestPackt = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPackt);
            //2.解析请求数据包
            String request = new String(requestPackt.getData(), 0, requestPackt.getLength());
            //3.根据请求，计算响应
            String response = process(request);
            //4.构造响应数据包
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPackt.getSocketAddress());
            //5.发送响应
            socket.send(responsePacket);
            //6.打印日志
            System.out.printf("[%s:%d] req:%s res:%s\n", requestPackt.getAddress().toString(), requestPackt.getPort(),
                    request, response);
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(9090);
        udpEchoServer.start();
    }
}
